package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.util.UUIDUtils;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;


@RestController
@RequestMapping("common")

public class CommonController {
    //读取配置文件中配置的目录
    @Value("${reggie.path}")
    private String baseDir;

    //1要求，使用MultipartFile类型接受上床文件
    //2.MultipartFile类型参数要和前端文件域表单元素name属性一致，如果不一样要@RequestParam("别名")
    @RequestMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        //1.获取上传文件的文件名
        String filename = file.getOriginalFilename();
        //获取拓展名
        String fileExtname= filename.substring(filename.lastIndexOf("."));
        //创建唯一随机文件n
        String newFilename = UUIDUtils.getUUID()+fileExtname;

        //2.将文件保存道f\img\目录下
        File dir = new File(baseDir);
        if (dir.exists()){
            dir.mkdir();
        }
        //进行保存
        file.transferTo(new File(baseDir+newFilename));
        //返回测试
        return R.success(newFilename);
    }
    @RequestMapping("/download")
    public void download(@RequestParam("name") String filename, HttpServletResponse response) throws Exception {

        //输入流
        FileInputStream inputStream = new FileInputStream(baseDir + filename);
        //输出流
        ServletOutputStream outputStream = response.getOutputStream();

        //工具包
        IOUtils.copy(inputStream, outputStream);

    }


}
